<template>
  <div>
    <!-- :model 收集表单数据 -->
    <el-form :inline="true" class="demo-form-inline" :model="cateForm">
      <el-form-item label="一级分类">
        <!-- v-model双向数据绑定,将数据收集到cateForm -->
        <el-select v-model="cateForm.category1Id" placeholder="请选择" :disabled="!show" @change="cate1Handler">
          <!-- value 收集表单数据 -->
          <el-option v-for="cate1 in list1" :key="cate1.id" :label="cate1.name" :value="cate1.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="二级分类">
        <el-select v-model="cateForm.category2Id" placeholder="请选择" :disabled="!show" @change="cate2Handler">
          <el-option v-for="cate2 in list2" :key="cate2.id" :label="cate2.name" :value="cate2.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="三级分类">
        <el-select v-model="cateForm.category3Id" placeholder="请选择" :disabled="!show" @change="cate3Handler">
          <el-option v-for="cate3 in list3" :key="cate3.id" :label="cate3.name" :value="cate3.id" />
        </el-select>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  name: 'CategorySetect',
  // 接受参数是三级联动是否能点击
  props: {
    show: {
      type: Boolean
    }
  },
  data() {
    return {
      // 一级分类列表数据
      list1: [],
      // 二级分类列表数据
      list2: [],
      // 三级分类列表数据
      list3: [],
      // 收集表单数据
      cateForm: {
        category1Id: '',
        category2Id: '',
        category3Id: ''
      }
    }
  },
  mounted() {
    this.getCategory1List()
  },
  methods: {
    // 获取一级分类
    async getCategory1List() {
      const res = await this.$API.attr.reqCategory1List()
      // console.log(res)
      if (res.code === 200) {
        this.list1 = res.data
      }
    },

    // 一级分类select事件处理函数
    async cate1Handler() {
      // 清除数据
      this.list2 = []
      this.list3 = []
      this.cateForm.category2Id = ''
      this.cateForm.category3Id = ''
      // 结构出一级分类id
      const { category1Id } = this.cateForm
      const res = await this.$API.attr.reqCategory2List(category1Id)
      if (res.code === 200) {
        this.list2 = res.data
      }
      // 将id传入父组件前需要判断是几级id
      this.$emit('getCateGoryId', { categoryId: category1Id, level: 1 })
    },

    // 二级分类select事件处理函数
    async cate2Handler() {
      // 清除数据
      this.list3 = []
      this.cateForm.category3Id = ''
      const { category2Id } = this.cateForm
      const res = await this.$API.attr.reqCategory3List(category2Id)
      if (res.code === 200) {
        this.list3 = res.data
      }
      this.$emit('getCateGoryId', { categoryId: category2Id, level: 2 })
    },

    // 三级分类select事件处理函数
    cate3Handler() {
      const { category3Id } = this.cateForm
      this.$emit('getCateGoryId', { categoryId: category3Id, level: 3 })
    }
  }
}
</script>

<style></style>
